package com.huatai.common.util;

/**
 * @program: ht-system
 * @description: 转换工具类
 * @author: songxiude
 * @create: 2023-01-31 14:28
 **/

import com.huatai.common.convert.HtConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.lang.Nullable;

public class ConvertUtil {
    public ConvertUtil() {
    }

    @Nullable
    public static <T> T convert(@Nullable Object source, Class<T> targetType) {
        if (source == null) {
            return null;
        } else if (ClassUtil.isAssignableValue(targetType, source)) {
            return (T) source;
        } else {
            GenericConversionService conversionService = HtConversionService.getInstance();
            return conversionService.convert(source, targetType);
        }
    }

    @Nullable
    public static <T> T convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        } else {
            GenericConversionService conversionService = HtConversionService.getInstance();
            return (T) conversionService.convert(source, sourceType, targetType);
        }
    }

    @Nullable
    public static <T> T convert(@Nullable Object source, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        } else {
            GenericConversionService conversionService = HtConversionService.getInstance();
            return (T) conversionService.convert(source, targetType);
        }
    }
}

